package com.liqi.frame.comm.controller.manager;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liqi.frame.comm.Constants;
import com.liqi.frame.comm.dto.HttpResult;
import com.liqi.frame.comm.dto.LayuiTableData;
import com.liqi.frame.comm.dto.MenuDto;
import com.liqi.frame.comm.dto.ZtreeDto;
import com.liqi.frame.comm.enums.ResultEnum;
import com.liqi.frame.comm.po.Group;
import com.liqi.frame.comm.po.Role;
import com.liqi.frame.comm.po.User;
import com.liqi.frame.comm.service.GroupService;
import com.liqi.frame.comm.service.MenuService;
import com.liqi.frame.comm.service.RoleService;
import com.liqi.frame.comm.service.UserService;
import com.liqi.frame.comm.token.TokenUtil;
import com.liqi.frame.comm.util.IdUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * Created by liqi on 2017/12/13.
 * liqiwork@qq.com
 */
@Controller
@RequestMapping({"/roleManager/ajax", "/roleManager/api"})
@Api(value = "角色的相关方法", tags = {"角色的相关方法"})
public class RoleManagerAjaxController {
    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation(value="获得当前用户的组织信息", notes = "获得当前用户的组织信息", httpMethod = "GET")
    @RequestMapping({"getCurrGroupInfo"})
    @ResponseBody
    public HttpResult getCurrGroupInfo() {
        User user = TokenUtil.getToken();
//        user.getGroupId();
        Role role = new Role();
        role.setGroupId(user.getGroupId());
        role.setGroupName(user.getGroupName());
        return HttpResult.success(role);
    }

    @ApiOperation(value="通过id获得角色信息", notes = "通过id获得角色信息", httpMethod = "GET")
//    @RequiresPermissions(value = {"roleManager:getRoleById", "cimrFrame:operation:passkey"}, logical = Logical.OR)
    @RequestMapping({"getRoleById"})
    @ResponseBody
    public HttpResult getRoleById(@RequestBody Map params) {
        String id = params.get("id")+"";

        Role role = roleService.getRoleById(id);

        HttpResult result = new HttpResult(ResultEnum.SUCCESS);
        result.setData(role);
        return result;
    }

    /**
     * @param roleId 角色id
     * @return 菜单信息
     * 弹出菜单授权表单页需先查询当前角色已授权，然后组装成树形数据
     */
    @ApiOperation(value="通过id获得菜单信息", notes = "通过id获得菜单信息", httpMethod = "GET")
//    @RequiresPermissions(value = {"roleManager:getMenuPer", "cimrFrame:operation:passkey"}, logical = Logical.OR)
    @RequestMapping({"getMenuZtree"})
    @ResponseBody
    public HttpResult getMenuPer(@RequestBody Map params) {
        String roleId = params.get("roleId")+"";

        HttpResult result = new HttpResult(ResultEnum.SUCCESS);
        // 获取可选项
        List<MenuDto> allMenuList = menuService.getMenuListByCurrUser();
        // 获取当前已选中的项
        List<MenuDto> curMenuList = menuService.getMenuListByRoleId(roleId);
        List<ZtreeDto> ztreeList = new ArrayList<ZtreeDto>();
        List<String> idList = new ArrayList<>();
        for (int i = 0;i<allMenuList.size();i++){
            ZtreeDto ztreeDto = new ZtreeDto();
            ztreeDto.setId(allMenuList.get(i).getId());
            ztreeDto.setpId(allMenuList.get(i).getParentId());
            if (allMenuList.get(i).getLevel()==1){
                ztreeDto.setParent(true);
            }
            if (allMenuList.get(i).getLevel()==2){
                ztreeDto.setParent(false);
            }
            ztreeDto.setName(allMenuList.get(i).getMenuName());
            ztreeDto.setChecked(false);
            for (int j=0;j<curMenuList.size();j++){
                if (allMenuList.get(i).getId().equals(curMenuList.get(j).getId())){
                    ztreeDto.setChecked(true);
                    break;
                };
            }
            // 去重
            if (!idList.contains(ztreeDto.getId())) {
                ztreeList.add(ztreeDto);
                idList.add(ztreeDto.getId());
            }
        }
        result.setData(ztreeList);
        return result;
    }

    /**
     * @param roleId 角色id
     * @param menuIds 多个菜单id
     * 保存菜单配置
     */
    @RequiresPermissions(value = {"roleManager:save",
                                  "roleManager:saveMenuPer",
            Constants.OPERATION_PASSKEY}, logical = Logical.OR)
    @RequestMapping({"saveMenuPer"})
    @ResponseBody
    public HttpResult saveMenuPer(@RequestBody Map params) {
        String roleId = params.get("roleId")+"";
        String menuIds = params.get("menuIds")+"";

        String s = menuIds.substring(1, menuIds.length()-1);
        String[] menuIdsArray=s.split(",");
        for (int i = 0 ;i<menuIdsArray.length;i++){
            menuIdsArray[i]=menuIdsArray[i].substring(1, menuIdsArray[i].length()-1);
        }
        int resultStatus1 = roleService.saveRoleAndMenus(roleId,menuIdsArray);
        if(resultStatus1>0) {
            return HttpResult.success("保存成功！");
        } else {
            return HttpResult.failure("保存失败！");
        }
    }

    /**
     * @param roleId 菜单id
     * @return ids 多个id
     * 保存操作配置
     */
    @RequiresPermissions(value = {"roleManager:save",
                                  "roleManager:saveOpationPer",
            Constants.OPERATION_PASSKEY}, logical = Logical.OR)
    @RequestMapping({"saveOpationPer"})
    @ResponseBody
    public HttpResult saveOpationPer(@RequestBody Map params) {
        String roleId = params.get("roleId")+"";
        String ids = params.get("ids")+"";

        String[] idArray = ids.split(",");
        int resultStatus1 = roleService.saveRoleAndOperations(roleId,idArray);
        if(resultStatus1 > 0) {
            return HttpResult.success("配置成功！");
        } else {
            return HttpResult.failure("配置失败！");
        }
    }

    /**
     * @param userId 用户id
     * @param roleIds 多个角色id
     * @return 返回结果
     * 保存角色配置
     */
//    @RequiresPermissions(value = {"roleManager:save",
//                                  "roleManager:saveRolePer",
//            Constants.OPERATION_PASSKEY}, logical = Logical.OR)
    @RequestMapping({"saveRolePer"})
    @ResponseBody
    public HttpResult saveRolePer(@RequestBody Map params) {
        String id = params.get("userId")+"";
        String ids = params.get("roleIds")+"";

        int resultStatus1;
        if(ids==""||ids==null){
            resultStatus1 = userService.saveUserAndRoles(id,null);
        }else{
            String[] idArray = ids.split(",");
            List<String> idList= new ArrayList<>();
            for(int i=0;i<idArray.length;i++){
                if (idArray[i]!=null){
                    idList.add(idArray[i]);
                }
            }
            String[] roleArray = new String[idList.size()];
            for (int i=0;i<idList.size();i++){
                roleArray[i] = idList.get(i);
            }
            resultStatus1 = userService.saveUserAndRoles(id,roleArray);
        }
        if (resultStatus1>0) {
            return HttpResult.success("配置成功！");
        } else {
            return HttpResult.failure("配置失败！");
        }
    }

    private String getBodyData(HttpServletRequest request) {
        StringBuffer data = new StringBuffer();
        String line = null;
        BufferedReader reader = null;
        try {
            reader = request.getReader();
            while (null != (line = reader.readLine())) {
                data.append(line);
            }
        } catch (IOException e) {
        } finally {
        }
        return data.toString();
    }

    private String getBodytxt(HttpServletRequest request) throws IOException {
        BufferedReader br = request.getReader();
        String str, wholeStr = "";
        while((str = br.readLine()) != null){
            wholeStr += str;
        }
        return wholeStr;
    }

    private String readBodyAsString(HttpServletRequest request) {
        InputStream is = null;
        StringBuilder sb = new StringBuilder();
        try {
            is = request.getInputStream();

            byte[] b = new byte[4096];
            for (int n; (n = is.read(b)) != -1;) {
                sb.append(new String(b, 0, n));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return sb.toString();
    }

    @ApiOperation(value="分页获得角色列表", notes = "分页获得角色列表", httpMethod = "GET")
//    @RequiresPermissions(value = {"roleManager:getRoleManagerList", "cimrFrame:operation:passkey"}, logical = Logical.OR)
    @RequestMapping({"getRoleManagerList"})
    @ResponseBody
    public LayuiTableData getRoleManagerList(@RequestBody Map params) {
//        ReHttpServletRequestWrapper aa = new ReHttpServletRequestWrapper(request);
//        IOUtils.toString(aa.getReader());
//        readBodyAsString(request);
//        new String(new ContentCachingRequestWrapper(request).getContentAsByteArray());
//        ContentCachingRequestWrapper requestWrapper = (ContentCachingRequestWrapper) request;
//        //name 和 此值是一样的
//        String requestBody = new String(requestWrapper.getContentAsByteArray());

//        ServletUtil.getParameter("limit");
        Integer page = (Integer)params.get("page");
        Integer limit = (Integer)params.get("limit");
        String roleName = params.get("roleName")+"";

        LayuiTableData result = new LayuiTableData(ResultEnum.SUCCESS);
        User currentUser = TokenUtil.getToken();
        List<Group> groupList = groupService.getGroupAndSonsByGroupId(currentUser.getGroupId());
        if (groupList!=null && groupList.size()>0) {
            String[] groupIds = new String[groupList.size()];
            for (int i = 0; i < groupList.size(); i++) {
                groupIds[i] = groupList.get(i).getId();
            }
            PageHelper.startPage(page, limit);
            List list = roleService.getRoleListWithName(roleName, groupIds);
            if (list!=null && list.size()>0) {
                PageInfo pageInfo = new PageInfo(list);
//                List list1 = roleService.getRoleListWithName(roleName, groupIds);
//                result.setCount(list1.size());
                result.setCount(pageInfo.getTotal());
                result.setData(pageInfo.getList());
            }
        }
        result.setCode(Integer.valueOf(0));
        result.setMsg("");
        return result;
    }


    @RequiresPermissions(value = {"roleManager:getRolesByUserId", Constants.OPERATION_PASSKEY}, logical = Logical.OR)
    @RequestMapping({"getRolesByUserId"})
    @ResponseBody
    public HttpResult getRolesByUserId(@RequestBody Map params) {
        String id = params.get("id")+"";

        List<Role> currentList = roleService.getRoleListByUserId(id);
        HttpResult result = new HttpResult(ResultEnum.SUCCESS);
        result.setData(currentList);
        return result;
    }

    /**
     * 取角色数据（用于用户管理中的角色穿梭框）
     * @param id 用户id
     * @return
     */
    @ApiOperation(value="取角色数据（用于用户管理中的角色穿梭框）", notes = "取角色数据（用于用户管理中的角色穿梭框）", httpMethod = "GET")
    @RequestMapping({"getRolesTransfer4User"})
    @ResponseBody
    public HttpResult getRolesTransfer4User(@RequestBody Map params) {
        String id = params.get("id")+"";

        HttpResult result = new HttpResult(ResultEnum.SUCCESS);
        List<Role> haveRoles = roleService.getRoleListByUserId(id);
        JSONArray haveRolesJSONArray = new JSONArray();
        for (int i = 0; i < haveRoles.size(); i++) {
            haveRolesJSONArray.add(haveRoles.get(i).getId());
        }

        User currentUser = TokenUtil.getToken();
        List allRoles = new ArrayList();
        List<Group> groupList = groupService.getGroupAndSonsByGroupId(currentUser.getGroupId());
        if (groupList!=null && groupList.size()>0) {
            String[] groupIds = new String[groupList.size()];
            for (int i = 0; i < groupList.size(); i++) {
                groupIds[i] = groupList.get(i).getId();
            }
            allRoles = roleService.getRoleListWithName("", groupIds);
        }
        JSONArray allRolesJSONArray = new JSONArray();
        for (int i = 0; i < allRoles.size(); i++) {
            JSONObject json = new JSONObject();
            json.put("value", ((Role)allRoles.get(i)).getId());
            json.put("title", ((Role)allRoles.get(i)).getRoleName());
            allRolesJSONArray.add(json);
        }

        Map resultMap = new HashMap();
        resultMap.put("haveRoles", haveRolesJSONArray);
        resultMap.put("allRoles", allRolesJSONArray);
        result.setData(resultMap);
        return result;
    }

//    @RequiresPermissions(value = {"roleManager:save",
//                                  "roleManager:saveRole",
//            Constants.OPERATION_PASSKEY}, logical = Logical.OR)
    @RequestMapping({"saveRole"})
    @ResponseBody
    public HttpResult saveRole(@RequestBody Map params) {
        String id = params.get("id")+"";
        String roleName = params.get("roleName")+"";
        String comment = params.get("comment")+"";
        Object orderIdObject = params.get("orderId");
        Float orderId = new Float(0);
        if (Objects.isNull(orderIdObject)) {
            orderId = Float.parseFloat(params.get("orderId") + "");
        }
        String groupId = params.get("groupId")+"";
        String groupName = params.get("groupName")+"";

        int resultStatus = 0;
        if (id!=null && !"".equals(id)) {
            resultStatus = roleService.updateRole(id, null, roleName, comment, orderId, groupId, groupName);
        } else {
            resultStatus = roleService.insertRole(IdUtil.getId()+"", null, roleName, comment, orderId, groupId, groupName);
        }

        if (resultStatus>0) {
            return HttpResult.success("保存成功！");
        } else {
            return HttpResult.failure("保存失败！");
        }
    }

    @RequestMapping({"updateOrderId"})
    @ResponseBody
    public HttpResult updateOrderId(@RequestBody Map params) {
        String id = params.get("id")+"";
        Object orderIdObject = params.get("orderId");
        Float orderId = new Float(0);
        if (Objects.isNull(orderIdObject)) {
            orderId = Float.parseFloat(params.get("orderId") + "");
        }

        int resultStatus = 0;
        resultStatus = roleService.updateOrderId(id, orderId);
        HttpResult result = new HttpResult(ResultEnum.SUCCESS);
        if (resultStatus>0) {
            return HttpResult.success("排序号已修改！");
        } else {
            return HttpResult.failure("修改失败！");
        }
    }

    @RequiresPermissions(value = {"roleManager:delete",
                                  "roleManager:deleteRole",
            Constants.OPERATION_PASSKEY}, logical = Logical.OR)
    @RequestMapping({"deleteRole"})
    @ResponseBody
    public HttpResult deleteRole(@RequestBody Map params) {
        String id = params.get("id")+"";

        int resultStatus = roleService.deleteRoleById(id);
        if(resultStatus > 0) {
            return HttpResult.success("删除成功！");
        } else {
            return HttpResult.failure("删除失败");
        }
    }

//    @RequiresPermissions(value = {"roleManager:getRoleListByKey", "cimrFrame:operation:passkey"}, logical = Logical.OR)
    @RequestMapping({"getRoleListByKey"})
    @ResponseBody
    public HttpResult getRoleListByKey(@RequestBody Map params) {
        String roleKey = params.get("roleKey")+"";

        List<Role> roleList = roleService.getRoleListByKey(roleKey);
        HttpResult result = new HttpResult(ResultEnum.SUCCESS);
        if(roleList!=null){
            if(roleList.size()==0){
                result.setData(null);
            }else{
                result.setData(roleList);
            }
        }
        return result;
    }

    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private UserService userService;
    @Autowired
    private GroupService groupService;
}
